package com.srwl.mytx.widget;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TopicDonationRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


@Deprecated
public class TopicReceivedDonationRecord extends DialogFragment implements TopicDonationRecordAdapter.InteractionListener {
    private static final String TAG = TopicReceivedDonationRecord.class.getSimpleName();
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.rv_donations)
    RecyclerView rv_donations;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.tv_donation_amount)
    TextView tv_donationAmount;
    @BindView(R.id.tv_donation_count)
    TextView tv_donationCount;

    private TopicDonationRecordAdapter donationRecordAdapter;

    private List<Donation> donationList = new ArrayList<>();
    private String attachId;
    private int page = 1;
    private boolean hasNextPage;
    private InteractionListener listener;
    private double totalDonationAmount;
    private int totalDonationSize;

    public static TopicReceivedDonationRecord newInstance(ArrayList<Donation> donations, String attachId, double totalDonationAmount, int totalDonationSize) {
        TopicReceivedDonationRecord myFileRepositoryDialog = new TopicReceivedDonationRecord();
        Bundle bundle = new Bundle();

        bundle.putParcelableArrayList("donationList", donations);
        bundle.putString("attachId", attachId);
        bundle.putDouble("amount", totalDonationAmount);
        bundle.putDouble("size", totalDonationSize);
        myFileRepositoryDialog.setArguments(bundle);
        return myFileRepositoryDialog;
    }


    public static TopicReceivedDonationRecord newInstance() {
        return new TopicReceivedDonationRecord();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int theme = android.R.style.Theme_Holo_Light_Dialog;
        setStyle(DialogFragment.STYLE_NO_TITLE, theme);
        if (getArguments() != null) {
            donationList = getArguments().getParcelableArrayList("donationList");
            attachId = getArguments().getParcelable("attachId");
            totalDonationAmount = getArguments().getDouble("amount", 0.00);
            totalDonationSize = getArguments().getInt("size", 0);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: 执行了，，，");
        View view = inflater.inflate(R.layout.layout_topic_received_donation, container, false);
        ButterKnife.bind(this, view);
        initRefreshLayout();
        donationRecordAdapter = new TopicDonationRecordAdapter(getActivity(), donationList, this);
        rv_donations.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rv_donations.setAdapter(donationRecordAdapter);
        tv_donationAmount.setText(Utils.moneyFormat(totalDonationAmount));
        tv_donationCount.setText(Utils.numberFormat(totalDonationSize));
        loadData(true);
        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        Window win = getDialog().getWindow(); // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams params = win.getAttributes();
        // params.gravity = Gravity.CENTER; // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        win.setAttributes(params);
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }


    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", 10);
        body.put("topicId", attachId);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .queryTopicDonations(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        JSONObject body = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取捐赠数据完成：" + body.toJSONString());
                        if (page == 1 && body.containsKey("totalAmount")) {
                            totalDonationAmount = body.getBigDecimal("totalAmount").doubleValue();
                            //tv_donationAmount.setText(Utils.moneyFormat(totalDonationAmount));
                        }

                        JSONObject pageInfo = body.getJSONObject("pageInfo");
//                        if (donationType == 1) {
//                            donationCount = pageInfo.getInteger("total");
//                            tv_donationCount.setText(donationCount + "");
//                        }

                        hasNextPage = pageInfo.getBoolean("hasNextPage");


                        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);

                        donationList.addAll(donations);
                        donationRecordAdapter.notifyDataSetChanged();
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });

    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    @Override
    public void onItemViewClick(String forwardId) {

    }


    public interface InteractionListener {
        void onConfirm(List<MyFile> videoFiles, List<MyFile> pictureFiles);
    }
}
